package org.lwd.datalink.api.biz;

import org.apache.ddlutils.model.Index;
import org.apache.ddlutils.model.IndexColumn;
import org.apache.ddlutils.model.Table;
import org.apache.ddlutils.model.UniqueIndex;
import org.lwd.datalink.domain.media.ColumnMappingMode;
import org.lwd.datalink.domain.media.MediaColumnMappingInfo;
import org.lwd.datalink.errors.ValidationException;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author: weidong.lin
 * @Description: 介质处理中心
 * @Date: create in 2024/3/16 10:40
 */
public class MediaBiz {

    /**
     * 判断Column-Mapping配置是否合法
     * 当不合法时抛出ValidationException
     *
     * @param table
     * @param mappingList
     * @param mode
     */
    public static void checkMediaColumnMappings(Table table, List<MediaColumnMappingInfo> mappingList, ColumnMappingMode mode) {
        if (mappingList == null || mappingList.isEmpty()) {
            return;
        }

        Index[] indices = table.getIndices();
        if (indices == null || indices.length < 1) {
            return;
        }

        List<UniqueIndex> uniqueIndices = new ArrayList<>();
        for (Index index : indices) {
            if (index instanceof UniqueIndex) {
                uniqueIndices.add((UniqueIndex) index);
            }
        }
        if (uniqueIndices.isEmpty()) {
            return;
        }

        for (UniqueIndex uniqueIndex : uniqueIndices) {
            if (uniqueIndex.getColumns().length > 1) {
                for (IndexColumn column : uniqueIndex.getColumns()) {
                    Optional<MediaColumnMappingInfo> optional = mappingList
                            .stream()
                            .filter(m -> m.getSourceColumn().equalsIgnoreCase(column.getName()))
                            .findFirst();

                    if ((mode.isInclude() && !optional.isPresent()) ||
                            (mode.isExclude() && optional.isPresent())) {
                        throw new ValidationException(
                                String.format("Column [%s] is part of the unique index [%s] in table [%s],can not be ignored in the data sync.",
                                        column.getName(),
                                        uniqueIndex.getName(),
                                        table.getName())
                        );
                    }
                }
            }
        }
    }
}
